import {
  randomStr
} from "@/utils/util"

const classifiedComps = [{
  className: "布局组件",
  comps: [{
    name: "柵格",
    icon: "el-icon-tickets",
    type: "row",
    role: "container",
    props: {}
  }]
}, {
  className: "基础组件",
  comps: [{
    name: "单行文本",
    icon: "el-icon-document-remove",
    type: "input",
    props: {
      lable: "姓名"
    }
  }, {
    name: "时间选择",
    icon: "el-icon-time",
    type: "timePicker",
    props: {
      lable: "时间"
    }
  }, {
    name: "滑块",
    icon: "el-icon-rank",
    type: "slider",
    props: {
      lable: "百分比"
    }
  }, {
    name: "评分",
    icon: "el-icon-star-off",
    type: "rate",
    props: {
      lable: "评分"
    }
  }, {
    name: "下拉选择",
    icon: "el-icon-arrow-down",
    type: "select",
    props: {
      label: "类型"
    }
  }]
}, {
  className: "行为组件",
  comps: [{
    name: "按钮",
    icon: "el-icon-mouse",
    type: "button"
  }]
}]

export default class WidgetLib {
  constructor() {
    this.ids = []
    this.classifiedComps = classifiedComps
  }
  pushComp() {
    // this.classifiedComps[1].comps.push()
  }
  mountWidgetLibHtml(selector) {
    const mountEl = document.querySelector(selector)
    if (!mountEl) return
    const html = this.initClassifiedCompHtml()
    mountEl.innerHTML = html
    this._bindEvent()
  }
  initClassifiedCompHtml() {
    return this.classifiedComps.reduce((result, cur) => {
      return result += this._createClassHtml(cur)
    }, "")
  }
  _createClassHtml(aClassComp) {
    const {
      className,
      comps
    } = aClassComp
    return `<div>
      <div class="ultrame-comp-class-name">${className}</div>
      ${this._createCompHtml(comps)}
    </div>`
  }
  _createCompHtml(comps) {
    return `<div class="ultrame-comp-container">
      ${comps.reduce((result, cur) => {
        const id = randomStr(8, "ultrame", "_")
        this.ids.push(id)
        return result += `<div id="${id}" data-role="${cur.role}" data-action="create" data-widgetType="${cur.type}" draggable="true" class="ultrame-comp-item">
          <i class=${cur.icon}></i>
          <span>${cur.name}</span>
        </div>`
      }, "")}
    </div>`
  }
  _bindEvent() {
    this.ids.forEach(id => {
      const comp = document.querySelector(`#${id}`)
      if (!comp) return
      comp.addEventListener("dragstart", this.handleDragstart)
      comp.addEventListener("dragend", this.handleDragend)
    })
  }
  handleDragstart(ev) {
    ev.dataTransfer.setData("widgetType", ev.target.dataset.widgettype);
    ev.dataTransfer.setData("action", ev.target.dataset.action);
    ev.dataTransfer.setData("role", ev.target.dataset.role);
  }
  handleDragend(ev) {
    ev.dataTransfer.clearData();
  }
}